package com.tm.controller;

import java.io.BufferedOutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.tm.ResultEntity;
import com.tm.pay.config.WechatConfig2;
import com.tm.service.OrderService;
import com.tm.util.CommonUtilsEx;
import com.tm.util.DateUtilsEx;
import com.tm.util.WXPayUtil;
import com.wordnik.swagger.annotations.ApiOperation;

/**
 * 订单接口
 * 
 * @author GXL
 * 2018年3月26日
 * TODO 处理支付通道回调、发起支付交易、订单展示等业务
 */
@RestController
@RequestMapping(value = "/order")
public class EcOrderController {
	
	private Logger logger = Logger.getLogger(EcOrderController.class);
	
	@Autowired
	private OrderService oService;
	
    
    /**
	 * 微信支付异步回调接口
	 * @param request
	 * @param response
	 * @return
	 */
    @ApiOperation(value="微信支付回调",notes="牛人跟单微信支付回调接口")
	@RequestMapping("/wechat_callback")
	public void wechat_charge_callback(HttpServletRequest request, HttpServletResponse response){
		String inputLine;
		String notityXml = "";
		String resXml = "";

		try {
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();
			
			System.out.println("接收到的报文：" + notityXml);
			Map<String, String> res = WXPayUtil.xmlToMap(notityXml);
			
			System.out.println("解析后的报文：" + res);
			
			if("SUCCESS".equals(String.valueOf(res.get("result_code")))){
				
				//校验返回签名
				boolean verify_result = WXPayUtil.isSignatureValid(notityXml, WechatConfig2.GZ_MCHKEY);
//				boolean verify_result = true;
				if(verify_result){
					String trade_no = res.get("out_trade_no");//订单号
					String transaction_id = res.get("transaction_id");//微信交易流水号
					Float money = (float) (Float.parseFloat(res.get("total_fee")) / 100);//实际支付金额
					
					ResultEntity re = oService.finishTransact(trade_no, transaction_id, money);
					
					if(!"0".equals(re.getCode())){
						System.out.println("交易处理失败");
					}
					
					resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
							+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
					
				}else{
					resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[签名失败]]></return_msg>" + "</xml> ";
					
				}
				
			}else{
				resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
						+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
			}
			
			BufferedOutputStream out = new BufferedOutputStream(
			response.getOutputStream());
			out.write(resXml.getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	
	/**
     * APP生成支付交易
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value="生成支付交易",notes="牛人跟单生成支付交易接口")
    @RequestMapping(value="/buildOrder", method=RequestMethod.POST)
    public ResultEntity buildOrder(HttpServletRequest request, HttpServletResponse response) {
    	ResultEntity re = null;
		String msg = "";
		System.out.println("-------------------------------app生成支付交易接口begin-----------------------------------------");
		try {
				
				Integer memberId = Integer.parseInt(request.getParameter("memberId"));// 会员ID
				String ip = CommonUtilsEx.getIpAddr(request);//支付IP地址
				Float allAmount = Float.parseFloat(request.getParameter("allAmount"));//订单总额
				Float payMoney = Float.parseFloat(request.getParameter("payMoney"));//支付金额
				String type = request.getParameter("type");// 操作类型 1：购彩 2：充值 
				String openid = String.valueOf(request.getSession().getAttribute("openid"));//会员对应当前公众号的唯一标识
				String couponsId = request.getParameter("couponsId");//优惠券id 非必传
				Integer addrId = Integer.parseInt(request.getParameter("addrId"));//收货地址id
//				re = oService.buildOrder(memberId, allAmount, payMoney, ip, type, openid, couponsId, addrId);
				
		} catch (NumberFormatException cce) {
			System.out.println(cce.getMessage());
			re = new ResultEntity("-1", "参数类型有误！");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			System.out.println("-------------------------------请求出错-----------------------------------------");
			System.out.println(e.getMessage());
			msg = e.getMessage();
			re = new ResultEntity("-1", msg, response);
		}
		System.out.println("-------------------------------app生成支付交易接口end-----------------------------------------");
		
        return re;
	}
    
    
    /**
     * 个人订单列表
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value="个人订单列表",notes="个人订单列表接口")
    @RequestMapping(value="/list", method=RequestMethod.POST)
    public ResultEntity list(HttpServletRequest request, HttpServletResponse response) {
    	ResultEntity re = null;
		String msg = "";
		System.out.println("-------------------------------个人订单列表接口begin-----------------------------------------");
		try {
			
			if(request.getSession().getAttribute("memberId") == null){
				re = new ResultEntity("-1", "请重新登录！");
				return re;
			}
				
			Integer memberId = (Integer) request.getSession().getAttribute("memberId");// 会员ID
			Integer startIndex = Integer.parseInt(request.getParameter("startIndex"));
			Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
			String orderState = request.getParameter("orderState");
			
			re = oService.getOrderListByMemberId(memberId, orderState, startIndex, pageSize);
				
		} catch (NumberFormatException cce) {
			System.out.println(cce.getMessage());
			re = new ResultEntity("-1", "参数类型有误！");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			System.out.println("-------------------------------请求出错-----------------------------------------");
			System.out.println(e.getMessage());
			msg = e.getMessage();
			re = new ResultEntity("-1", msg, response);
		}
		System.out.println("-------------------------------个人订单列表接口end-----------------------------------------");
		
        return re;
	}
    
    /**
     * 个人提现申请
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value="个人提现申请",notes="个人提现申请接口")
    @RequestMapping(value="/withdrawals", method=RequestMethod.POST)
    public ResultEntity withdrawals(HttpServletRequest request, HttpServletResponse response) {
    	ResultEntity re = null;
		String msg = "";
		System.out.println("-------------------------------个人提现申请接口begin-----------------------------------------");
		try {
			
			if(request.getSession().getAttribute("memberId") == null){
				re = new ResultEntity("-1", "请重新登录！");
				return re;
			}
				
			Integer memberId = (Integer) request.getSession().getAttribute("memberId");// 会员ID
			Float money = Float.parseFloat(request.getParameter("money"));//提现金额
			String type = request.getParameter("type");//提现方式 1：支付宝 2：微信 3：银行卡
			String memberCardId = request.getParameter("memberCardId");//会员银行卡id 需走绑定银行卡流程 提现方式为银行卡时必传
			String aliAcc = request.getParameter("aliAcc");//支付宝账号  提现方式为支付宝时必传
			String aliRealName = request.getParameter("aliRealName");//支付宝账号实名认证的姓名  提现方式为支付宝时必传
			String weixinAccount = request.getParameter("weixinAccount");//微信账号 应急使用
			String openId = request.getParameter("openId");//微信openId 该方式暂不使用
			String ip = CommonUtilsEx.getIpAddr(request);//客户端IP
			
			re = oService.addWithdrawalsApply(memberId, money, type, memberCardId, aliAcc, aliRealName, openId, ip, weixinAccount);
				
			
		} catch (NumberFormatException cce) {
			System.out.println(cce.getMessage());
			re = new ResultEntity("-1", "参数类型有误！");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			System.out.println("-------------------------------请求出错-----------------------------------------");
			System.out.println(e.getMessage());
			msg = e.getMessage();
			re = new ResultEntity("-1", msg, response);
		}
		System.out.println("-------------------------------个人提现申请接口end-----------------------------------------");
		
        return re;
	}
    
    /**
     * 取消订单
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value="取消订单",notes="取消订单接口")
    @RequestMapping(value="/cancel", method=RequestMethod.POST)
    public ResultEntity cancel(HttpServletRequest request, HttpServletResponse response) {
    	ResultEntity re = null;
		String msg = "";
		System.out.println("-------------------------------取消订单接口begin-----------------------------------------");
		try {
			
			if(request.getSession().getAttribute("memberId") == null){
				re = new ResultEntity("-1", "请重新登录！");
				return re;
			}
				
			Integer memberId = (Integer) request.getSession().getAttribute("memberId");// 会员ID
			String orderId = request.getParameter("orderId");//订单号
			Integer reasonId = Integer.parseInt(request.getParameter("reasonId"));//取消原因ID号
			String notes = request.getParameter("notes");//取消原因
			
			
	        re = oService.cancelOrder(memberId, orderId, reasonId, notes);
				
			
		} catch (NumberFormatException cce) {
			System.out.println(cce.getMessage());
			re = new ResultEntity("-1", "参数类型有误！");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			System.out.println("-------------------------------请求出错-----------------------------------------");
			System.out.println(e.getMessage());
			msg = e.getMessage();
			re = new ResultEntity("-1", msg, response);
		}
		System.out.println("-------------------------------取消订单接口end-----------------------------------------");
		
        return re;
	}
    
    /**
     * 确认收货
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value="确认收货",notes="确认收货接口")
    @RequestMapping(value="/take", method=RequestMethod.POST)
    public ResultEntity take(HttpServletRequest request, HttpServletResponse response) {
    	ResultEntity re = null;
		String msg = "";
		System.out.println("-------------------------------确认收货接口begin-----------------------------------------");
		try {
			
			if(request.getSession().getAttribute("memberId") == null){
				re = new ResultEntity("-1", "请重新登录！");
				return re;
			}
				
			Integer memberId = (Integer) request.getSession().getAttribute("memberId");// 会员ID
			String orderId = request.getParameter("orderId");//订单号
			
	        re = oService.takeOrder(memberId, orderId);
				
		} catch (NumberFormatException cce) {
			System.out.println(cce.getMessage());
			re = new ResultEntity("-1", "参数类型有误！");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			System.out.println("-------------------------------请求出错-----------------------------------------");
			System.out.println(e.getMessage());
			msg = e.getMessage();
			re = new ResultEntity("-1", msg, response);
		}
		System.out.println("-------------------------------确认收货接口end-----------------------------------------");
		
        return re;
	}
    
    /**
     * 个人收益列表
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value="个人收益列表",notes="个人收益列表接口")
    @RequestMapping(value="/incomeList", method=RequestMethod.POST)
    public ResultEntity incomeList(HttpServletRequest request, HttpServletResponse response) {
    	ResultEntity re = null;
		String msg = "";
		System.out.println("-------------------------------个人收益列表接口begin-----------------------------------------");
		try {
			
			if(request.getSession().getAttribute("memberId") == null){
				re = new ResultEntity("-1", "请重新登录！");
				return re;
			}
				
			Integer memberId = (Integer) request.getSession().getAttribute("memberId");// 会员ID
			String incomeType = request.getParameter("incomeType");//收入类型(1:金额2:积分)
			Integer startIndex = Integer.parseInt(request.getParameter("startIndex"));
			Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
			
			String month = request.getParameter("month");//格式：2017-08
			
			Calendar calendar = Calendar.getInstance();  
			Date date = DateUtilsEx.formatToDate(month, "yyyy-MM");
	        calendar.setTime(date);
	        int dd = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
			
	        String startTime = month + "-01";
	        String endTime = month + "-" + dd + "";
			
			re = oService.getIncomeListByMemberId(memberId, incomeType, startTime, endTime, startIndex, pageSize);
				
		} catch (NumberFormatException cce) {
			System.out.println(cce.getMessage());
			re = new ResultEntity("-1", "参数类型有误！");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			System.out.println("-------------------------------请求出错-----------------------------------------");
			System.out.println(e.getMessage());
			msg = e.getMessage();
			re = new ResultEntity("-1", msg, response);
		}
		System.out.println("-------------------------------个人收益列表接口end-----------------------------------------");
		
        return re;
	}
    
    /**
     * 门店销售统计列表
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value="门店销售统计列表",notes="门店销售统计列表接口")
    @RequestMapping(value="/saleList", method=RequestMethod.POST)
    public ResultEntity saleList(HttpServletRequest request, HttpServletResponse response) {
    	ResultEntity re = null;
		String msg = "";
		System.out.println("-------------------------------门店销售统计列表接口begin-----------------------------------------");
		try {
			
			if(request.getSession().getAttribute("memberId") == null){
				re = new ResultEntity("-1", "请重新登录！");
				return re;
			}
				
			Integer memberId = (Integer) request.getSession().getAttribute("memberId");// 会员ID
			Integer startIndex = Integer.parseInt(request.getParameter("startIndex"));
			Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
			
			String month = request.getParameter("month");//格式：2017-08
			
			Calendar calendar = Calendar.getInstance();  
			Date date = DateUtilsEx.formatToDate(month, "yyyy-MM");
	        calendar.setTime(date);
	        int dd = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
			
	        String startTime = month + "-01";
	        String endTime = month + "-" + dd + "";
			
			re = oService.getSaleListByMemberId(memberId, startTime, endTime, startIndex, pageSize);
				
		} catch (NumberFormatException cce) {
			System.out.println(cce.getMessage());
			re = new ResultEntity("-1", "参数类型有误！");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			System.out.println("-------------------------------请求出错-----------------------------------------");
			System.out.println(e.getMessage());
			msg = e.getMessage();
			re = new ResultEntity("-1", msg, response);
		}
		System.out.println("-------------------------------门店销售统计列表接口end-----------------------------------------");
		
        return re;
	}
    
    /**
     * 门店销售订单列表
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value="门店销售订单列表",notes="门店销售订单列表接口")
    @RequestMapping(value="/saleOrderList", method=RequestMethod.POST)
    public ResultEntity saleOrderList(HttpServletRequest request, HttpServletResponse response) {
    	ResultEntity re = null;
		String msg = "";
		System.out.println("-------------------------------门店销售订单列表接口begin-----------------------------------------");
		try {
			
			if(request.getSession().getAttribute("memberId") == null){
				re = new ResultEntity("-1", "请重新登录！");
				return re;
			}
				
			Integer memberId = (Integer) request.getSession().getAttribute("memberId");// 会员ID
			Integer startIndex = Integer.parseInt(request.getParameter("startIndex"));
			Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
			String orderState = request.getParameter("orderState");
			
			re = oService.getSaleOrderListByMemberId(memberId, orderState, startIndex, pageSize);
				
		} catch (NumberFormatException cce) {
			System.out.println(cce.getMessage());
			re = new ResultEntity("-1", "参数类型有误！");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			System.out.println("-------------------------------请求出错-----------------------------------------");
			System.out.println(e.getMessage());
			msg = e.getMessage();
			re = new ResultEntity("-1", msg, response);
		}
		System.out.println("-------------------------------门店销售订单列表接口end-----------------------------------------");
		
        return re;
	}
    
    /**
     * 确认发货
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value="确认发货",notes="确认发货接口")
    @RequestMapping(value="/confirm", method=RequestMethod.POST)
    public ResultEntity confirm(HttpServletRequest request, HttpServletResponse response) {
    	ResultEntity re = null;
		String msg = "";
		System.out.println("-------------------------------确认发货接口begin-----------------------------------------");
		try {
			
			if(request.getSession().getAttribute("memberId") == null){
				re = new ResultEntity("-1", "请重新登录！");
				return re;
			}
				
			Integer memberId = (Integer) request.getSession().getAttribute("memberId");// 会员ID
			String orderId = request.getParameter("orderId");//订单号
			
	        re = oService.confirmOrder(memberId, orderId);
				
		} catch (NumberFormatException cce) {
			System.out.println(cce.getMessage());
			re = new ResultEntity("-1", "参数类型有误！");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			System.out.println("-------------------------------请求出错-----------------------------------------");
			System.out.println(e.getMessage());
			msg = e.getMessage();
			re = new ResultEntity("-1", msg, response);
		}
		System.out.println("-------------------------------确认发货接口end-----------------------------------------");
		
        return re;
	}
    
}
